package thread;

//懒汉式
class SingletonLazy{
    private static volatile SingletonLazy instance = null;
    private static Object locker = new Object();

    private SingletonLazy(){

    }

    public  static SingletonLazy getInstance(){
        if(instance == null){//判断是否加锁
            synchronized (locker){//保证原子性
                if(instance == null){//判断是否创建实例
                    instance = new SingletonLazy();
                }
            }
        }

        return instance;
    }
}

//饿汉式
class SingletonHungry{
    private static SingletonHungry instance = new SingletonHungry();

    private SingletonHungry(){

    }

    public static SingletonHungry getInstance(){
        return instance;
    }
}


//饿汉和懒汉的区别是创建实例的时机不同
public class Demo17 {

    public static void main(String[] args) {
        SingletonLazy s1 = SingletonLazy.getInstance();

        SingletonHungry s2 = SingletonHungry.getInstance();
    }
}
